package com.zf.gateway.exception;

import com.alibaba.fastjson2.JSONObject;
import com.zf.common.core.result.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关全局异常处理
 *
 * @author Zhou Feng
 */
@Order(-1)
@Slf4j
@Component
public class GlobalGatewayExceptionHandler implements ErrorWebExceptionHandler {

    @SuppressWarnings({"NullableProblems"})
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // Json格式返回
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        return response.writeWith(Mono.fromSupplier(() -> {
            //返回响应结果，根据业务需求，自己定制
            RestResponse<Void> resultMsg = new RestResponse<>("500", ex.getMessage(), null, false);
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSONObject.toJSONString(resultMsg).getBytes(StandardCharsets.UTF_8));
        }));
    }
}
